package com.example.translateappjava.Utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageDecoder;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.FileProvider;

import com.example.translateappjava.Fragment.HomeFragment;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 图片捕获管理类 - 负责处理相机拍照和相册选择功能
 */
public class ImageCaptureManager {

    private HomeFragment homeFragment;
    private ActivityResultLauncher<Intent> cameraLauncher;
    private ActivityResultLauncher<String> galleryLauncher;
    private Uri photoUri;

    public ImageCaptureManager(HomeFragment homeFragment) {
        this.homeFragment = homeFragment;
        initializeLaunchers();
    }

    private void initializeLaunchers() {
        // 初始化相机启动器
        cameraLauncher = homeFragment.registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        handleCameraResult();
                    } else {
                        Log.d("Camera", "相机操作被取消或失败");
                    }
                }
        );

        // 初始化相册启动器
        galleryLauncher = homeFragment.registerForActivityResult(
                new ActivityResultContracts.GetContent(),
                result -> {
                    if (result != null) {
                        handleGalleryResult(result);
                    }
                }
        );
    }

    /**
     * 启动相机拍照
     */
    public void launchCamera() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Log.v("ImageCaptureManager", "launchCamera()");

        // 创建临时文件来存储高质量图片
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            Log.e("Camera", "Error creating image file", ex);
            return;
        }

        if (photoFile != null) {
            photoUri = FileProvider.getUriForFile(
                    homeFragment.requireContext(),
                    "com.example.translateappjava.fileprovider", // 替换为你的包名
                    photoFile
            );
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            cameraLauncher.launch(cameraIntent);
        }
    }

    /**
     * 启动相册选择
     */
    public void launchGallery() {
        galleryLauncher.launch("image/*");
    }

    /**
     * 处理相机拍照结果
     */
    private void handleCameraResult() {
        try {
            Log.v("ImageCaptureManager", "Photo URI: " + photoUri);
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(
                    homeFragment.requireActivity().getContentResolver(),
                    photoUri
            );
            Log.v("ImageCaptureManager", "Bitmap size: " + bitmap.getByteCount());

            // 压缩到合适大小（保持质量）
            bitmap = resizeBitmap(bitmap, 1024, 1024);

            if (bitmap != null) {
                // 通知HomeFragment处理图片
                homeFragment.onImageCaptured(bitmap);
            }
        } catch (IOException e) {
            Log.e("Camera", "Error loading image", e);
            Toast.makeText(homeFragment.getActivity(), "图片加载失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 处理相册选择结果
     */
    private void handleGalleryResult(Uri result) {
        try {
            ImageDecoder.Source source = ImageDecoder.createSource(
                    homeFragment.requireActivity().getContentResolver(),
                    result
            );
            Bitmap bitmap = ImageDecoder.decodeBitmap(source);

            // 压缩图片
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 40, byteArrayOutputStream);
            byte[] bitmapData = byteArrayOutputStream.toByteArray();
            Bitmap compressedBitmap = BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length);

            if (compressedBitmap != null) {
                // 通知HomeFragment处理图片
                homeFragment.onImageCaptured(compressedBitmap);
            }
        } catch (IOException e) {
            Log.e("Gallery", "Error loading image from gallery", e);
            Toast.makeText(homeFragment.getActivity(), "图片加载失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 创建图片文件
     */
    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = homeFragment.requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(imageFileName, ".jpg", storageDir);
    }

    /**
     * 压缩图片到指定尺寸
     */
    private Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        if (width <= maxWidth && height <= maxHeight) {
            return bitmap;
        }

        float ratioX = (float) maxWidth / width;
        float ratioY = (float) maxHeight / height;
        float ratio = Math.min(ratioX, ratioY);

        int newWidth = (int) (width * ratio);
        int newHeight = (int) (height * ratio);

        return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
    }
}